import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import {
  setStorage,
  getStorage,
  hasStorage,
  clearStorage,
} from '@/utils/storage'
import router from '@/router'
import { errMsg } from './message'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: "http://localhost:8089",
  // timeout: 50000,//50秒
  timeout: 600000, //600秒
})

service.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem('token')
    let userInfo = JSON.parse(getStorage('userInfo'))
    console.log('token:' + token)
    if (token) {
      config.headers['token'] = token
    }
    if (userInfo) {
      config.headers['userId'] = userInfo.id
    }
    if (config.method == 'post') {
      config.headers['Content-Type'] = 'application/json'
    }
    if (config.data instanceof FormData) {
      config.headers = {
        'Content-Type': 'multipart/form-data',
        token: token,
      }
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  },
)

let count = 0
let count1 = 0
// var sendDate = (new Date()).getTime();

service.interceptors.response.use(
  (response) => {
    const res = response.data
    // console.log(response, 'responseresponseresponse')
    if (response.data.type == 'application/vnd.ms-excel') {
      let contentDisposition = response.headers['content-disposition'];
      // fileName必用这种方式进行解析，否则乱码
      let fileName = window.decodeURI(contentDisposition.substring(contentDisposition.indexOf('=') + 1));
      console.log('fileName=' + fileName);
      const blob = new Blob([response.data], {
        type: 'application/vnd.ms-excel'
      });
      const objectUrl = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = objectUrl;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();// 点击
      document.body.removeChild(link); // 下载完成移除元素
      window.URL.revokeObjectURL(URL); // 释放掉blob对象
    }
    if (res.code != 200) {
      if (res.code == 10003 || res.code == 10004) {
        if (count === 0) {
          Message({
            message: '身份验证过期，请重新登录！',
            type: 'error',
          })
        }
        // clearStorage()
        // router.push({
        //   path: '/login',
        //   query: { path: router.currentRoute.fullPath },
        // })
        // location.reload()
      } else if (res.code == 10001 || res.code == 10000) {
        Message.error(res.msg)
      } else if (res.code == 0) {
        return res
      } else if (res.code == -1) {
        return res
      } else {
        Message.error(res.msg)
      }
      count++
      return Promise.reject(res)
    } else {
      // var receiveDate = (new Date()).getTime();
      // var responseTimeMs = receiveDate - sendDate;
      // console.log(responseTimeMs,'responseTimeMsresponseTimeMs')
      return res
    }
  },
  (error) => {
    console.log(error.message)
    if (error.message.indexOf('Network Error') != -1) {
      Message({
        // message: '网络连接错误或未连接',
        message: '服务器未启动',
        type: 'error',
        duration: 10 * 1000,
      })
      return Promise.reject(error)
    }
    if (error.message == `timeout of ${error.config.timeout}ms exceeded`) {
      Message({
        message: '网络连接超时！请检查网络',
        type: 'error',
        duration: 5 * 1000,
      })
    } else if (error.message == 'Request failed with status code 401') {
      errMsg('当前角色无权限，请联系管理员！')
    } else {
      if (count1 === 0) {
        Message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000,
        })
      }
      count1++
      console.log(error)
    }
    return Promise.reject(error)
  },
)

export default service
